package com.ruoyi.project.ledger.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.ledger.domain.LedgerBusinessAccount;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ledger.domain.LedgerForklift;
import com.ruoyi.project.ledger.service.ILedgerForkliftService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 叉车台账Controller
 *
 * @author ruoyi
 * @date 2020-05-08
 */
@RestController
@RequestMapping("/ledger/forklift")
public class LedgerForkliftController extends BaseController
{
    @Autowired
    private ILedgerForkliftService ledgerForkliftService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询叉车台账列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:forklift:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedgerForklift ledgerForklift)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerForklift.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerForklift.setAreas(areas);
        ledgerForklift.setManagementCharacters(managementCharacters);
        startPage();
        List<LedgerForklift> list = ledgerForkliftService.selectLedgerForkliftList(ledgerForklift);
        return getDataTable(list);
    }

    /**
     * 导出叉车台账列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:forklift:export')")
    @Log(title = "叉车台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LedgerForklift ledgerForklift)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerForklift.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerForklift.setAreas(areas);
        ledgerForklift.setManagementCharacters(managementCharacters);
        List<LedgerForklift> list = ledgerForkliftService.selectLedgerForkliftList(ledgerForklift);
        int i=0;
        for (LedgerForklift forklift : list){
            forklift.setId(Long.valueOf(++i));
        }
        ExcelUtil<LedgerForklift> util = new ExcelUtil<LedgerForklift>(LedgerForklift.class);
        return util.exportExcel(list, "叉车数据");
    }

    @Log(title = "叉车台账", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ledger:forklift:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        Long stationId = null;
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            stationId = user.getStationId();
        }
        else{
            return AjaxResult.error("当前角色无导入权限");
        }
        ExcelUtil<LedgerForklift> util = new ExcelUtil<>(LedgerForklift.class);
        List<LedgerForklift> forkliftList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = ledgerForkliftService.importForklift(forkliftList, updateSupport, operName,stationId);
        return AjaxResult.success(message);
    }


    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        List<LedgerForklift> list =new ArrayList<>();
        list.add(new LedgerForklift(Long.valueOf(1),"江苏舜羿达供应链管理有限公司","91320206MA1MK","苏B12345",new Date()));
        list.add(new LedgerForklift(Long.valueOf(2),"导入前请删除例子","913202A1MK","苏B12357",new Date()));
        ExcelUtil<LedgerForklift> util = new ExcelUtil<>(LedgerForklift.class);
        return util.exportExcel(list,"叉车数据模板");
    }

    /**
     * 获取叉车台账详细信息
     */
//    @PreAuthorize("@ss.hasPermi('ledger:forklift:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ledgerForkliftService.selectLedgerForkliftById(id));
    }

    /**
     * 新增叉车台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:forklift:add')")
    @Log(title = "叉车台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedgerForklift ledgerForklift)
    {
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long stationId = user.getStationId();
            ledgerForklift.setStationId(stationId);
            ledgerForklift.setCreateId(String.valueOf(user.getUserId()));
        }
        else{
            return AjaxResult.error("当前角色无新增权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerForkliftService.checklicensePlateUnique(ledgerForklift.getLicensePlate(),ledgerForklift.getBusinessId())))
        {
            return AjaxResult.error("新增叉车失败，叉车号牌:'" + ledgerForklift.getLicensePlate() + "'已存在");
        }
        return toAjax(ledgerForkliftService.insertLedgerForklift(ledgerForklift));
    }

    /**
     * 修改叉车台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:forklift:edit')")
    @Log(title = "叉车台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedgerForklift ledgerForklift)
    {
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long stationId = user.getStationId();
            ledgerForklift.setStationId(stationId);
            ledgerForklift.setCreateId(String.valueOf(user.getUserId()));
        }
        else{
            return AjaxResult.error("当前角色无修改权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerForkliftService.checklicensePlateUnique2(ledgerForklift)))
        {
            return AjaxResult.error("修改叉车失败，叉车号牌:'" + ledgerForklift.getLicensePlate() + "'已存在");
        }
        return toAjax(ledgerForkliftService.updateLedgerForklift(ledgerForklift));
    }

    /**
     * 删除叉车台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:forklift:remove')")
    @Log(title = "叉车台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ledgerForkliftService.deleteLedgerForkliftByIds(ids));
    }
}
